<?php
namespace app\admin\controller;

use app\common\model\AdPosition as AdPositionModel;
use app\common\model\Ad as AdModel;
use app\common\controller\AdminBase;
use think\Db;

/**
 * 广告管理
 * Class Ad
 * @package app\admin\controller
 */
class Ad extends AdminBase
{

    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 广告管理
     * @return mixed
     */
    public function index()
    {
        $slide_category_model = new AdPositionModel();
        $slide_category_list  = $slide_category_model->column('name', 'id');
        $slide_list           = AdModel::all();

        return $this->fetch('index', ['slide_list' => $slide_list, 'slide_category_list' => $slide_category_list]);
    }

    /**
     * 添加广告
     * @return mixed
     */
    public function add()
    {
        $slide_category_list = AdPositionModel::all();

        return $this->fetch('add', ['slide_category_list' => $slide_category_list]);
    }

    /**
     * 保存广告
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            $validate_result = $this->validate($data, 'Ad');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $slide_model = new AdModel();
                if ($slide_model->allowField(true)->save($data)) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑广告
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $slide_category_list = AdPositionModel::all();
        $slide               = AdModel::get($id);

        return $this->fetch('edit', ['slide' => $slide, 'slide_category_list' => $slide_category_list]);
    }

    /**
     * 更新广告
     * @param $id
     */
    public function update($id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            $validate_result = $this->validate($data, 'Ad');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $slide_model = new AdModel();
                if ($slide_model->allowField(true)->save($data, $id) !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除广告
     * @param $id
     */
    public function delete($id = 0, $ids = [])    
    {
        $id = $ids ? $ids : $id;
        if ($id) {
            if (Db::name('Ad')->delete($id) !== false) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }else {
            $this->error('请选择需要删除的广告');
        }
    }
}